# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:   smalleel-api-tools
# FileName:     requestUntil
# Author:      
# Datetime:    2022/7/18 17:04
# Description：封装公共请求方法
# -----------------------------------------------------------------------------------
from typing import Any, Union

import requests
from requests import Response

from common.util.configUtil.configUtil import ConfigUtil

"""
1：基于项目中的接口的各种请求方法和传参方式，封装通用的方法
"""


class RequestsUtil:
    session = requests.Session()

    def send_request(self, method: str, url: str, params: [Any], parameterFormat: str = "json",
                     **kwargs: [Any]) -> Union[dict, Response]:
        """
        针对不同请求方法和传参方式进行判断，调用Session对象的方法实现请求
        :param method: 请求方式
        :param url: 地址
        :param params: 参数
        :param parameterFormat: 参数请求方式，默认json
        :param kwargs:关键字传参
        :return: 返回json响应内容
        """
        method = method.upper()
        parameterFormat = parameterFormat.lower()
        if method == "GET":
            return self.session.request(method, url, params=params, **kwargs).json()
        elif method == "POST":
            if parameterFormat == "data":
                return self.session.request(method, url, data=params, **kwargs).json()
            elif parameterFormat == "export":
                return self.session.request(method, url, data=params, **kwargs)
            else:
                return self.session.request(method, url, json=params, **kwargs).json()
        else:
            print("只支持GET/POST两种方法！！！")

    @staticmethod
    def response_down_file(response: Response, apiName: str, params: str):
        config = ConfigUtil()
        filePath = None
        response.encoding = "utf-8"
        response.iter_content()
        if "GroupPrepay" in apiName:
            filePath = config.get_downFile_path("apiGroupPrepayExport").format(params)
        elif "GroupPublic" in apiName:
            filePath = config.get_downFile_path("apiGroupPublicExport").format(params)
        elif "ProPrepay" in apiName:
            filePath = config.get_downFile_path("apiProjectPrepayExport").format(params)
        elif "ProPublic" in apiName:
            filePath = config.get_downFile_path("apiProjectPublicExport").format(params)
        with open(filePath.format(params), "wb") as f:
            try:
                for chunk in response.iter_content():
                    f.write(chunk)
                print("文件导出成功！")
            except Exception as e:
                raise e

    # 声明方法实现json响应断言
    # @staticmethod
    # def assert_dict(expect: dict, actual: dict):
    #     for key in expect.keys():
    #         print(getValueByKey(actual, target_key=key, results=[])[0])
    #         if (key in getAllkeys(actual)) and (expect[key] == getValueByKey(actual, target_key=key, results=[])[0]):
    #             return "Pass"
    #         else:
    #             return "Fail"


# and (expect[key] in actual.values())
if __name__ == '__main__':
    requestUntil = RequestsUtil()
    # requestUntil.response_down_file()
